import appOptions from './appUtil'
const app = getApp()

const crc = appOptions.requirejs("crc16");
const bin = appOptions.requirejs("binary");

var serviceUUID = [] //主 service 的 uuid 列表
var writeUUID = ""; //写读 UUID
var notifyUUID = ""; //notify UUID
var readUUID = ""; //读UUID
var delayUUID = ""; //护眼仪控制时长UUID
var filterServiceUUID = ""; //过滤获取到的服务uuid(有些会返回多条数据)
var filterDeviceName = ""; //设备名称

var device_sn = ""; //  设备编号
var device_type = ''; //  设备类型
var device_key = '';  // 蓝牙设备的Key
var _discoveryStarted = false;      // 蓝牙是否在搜索
var deviceId = ''; //用于区分设备的 id

var _deviceId = '';
var _serviceId = '';
var _characteristicId = '';
var status = false; //当前状态
var action_type = ''; //操作类型
var code = -1;
var isnotExist = true //防止多次执行

// 回调
var btOpenCallback = null;          // 接收开锁回调
var btErrorCallback = null;         // 接收错误码处理
var btWriteCallback = null;    // 接收写入处理
var btRechargeCallback = null;        //接收充电回调

//var tempStr = ''; //拼接设备返回数据
//var rssiVal = ''; //RSSI值
var currentSerialVal = ''; //当前点击格子柜序号
var currentOrderSN = ''; // 当前订单编号
var msg_id = 1;   //消息条数
var yt_device_type = '0x80'; // 圆筒蓝牙类型
var sh_device_type = '0x66'  // SH的板子
var yt_recharge_device_type = '0x81'  //圆筒蓝牙类型，带充电
var wxc_device_type = '0x88'; // 无线充
var wxc_device_type_new = '0x89'; // 无线充新
//判断是否是圆筒蓝牙类型
function isYTDevice(deviceType) {
    return deviceType == yt_device_type || deviceType == yt_recharge_device_type
}


//当前设备的操作类型
var OptionEnum = {
    None: -1,
    Connection: 0, //连接
    Reconnection: 1, //重连
    CloseLock: 2, //关闭
    VendingOpenLock: 8, //打开售卖机
    ReadStatus: 9, //读售卖机状态
    ReadBattery: 10, //读售卖机电量
    Recharge: 11,     //充电
    ReadRecharge: 13,//读取充电状态
    ReadRechargeCallback: 14,//读取充电状态，单独回调
};
//这个是变量, 存储数据的变量
var action_type = OptionEnum.None;

function inArray(arr, key, val) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i][key] === val) {
            return i;
        }
    }
    return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
            return ('00' + bit.toString(16)).slice(-2)
        }
    )
    return hexArr.join('');
}

/**
 * 去掉 冒号
 */
function clearSymbol(str) {
    str = str.replace(/:/g, ""); //取消字符串中出现的所有冒号
    return str;
}

/**
 *  匹配规则: 取名称后面的mac
 */
function getNameMac(device_sn, len, name) {
    let clearColonMac = clearSymbol(device_sn); // 清除冒号
    let lastFourMac = clearColonMac.substring(clearColonMac.length - len);
    let strName = name.toUpperCase();
    strName = strName + lastFourMac.toUpperCase(); //转大写
    console.log('拼接后的' + strName);
    return strName
}


/**
 * 区分不同类型的服务相关uuid
 * 1-->充电宝 2-->售卖机
 */
function setServicesUUID() {
    console.log('type======>', device_type);
    if (device_type === sh_device_type) {    // 格子机
        serviceUUID[0] = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"; //主 service的uuid 列表
        writeUUID = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"; //写读 UUID
        notifyUUID = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"; //notify UUID
        //filterServiceUUID = "*E0";
    } else if (isYTDevice(device_type)) { // 圆筒蓝牙类型
        serviceUUID[0] = "0783b03e-8535-b5a0-7140-a304f013c3b7"; //主 service的uuid 列表
        writeUUID = "0783b03e-8535-b5a0-7140-a304f013c3ba"; //写读 UUID
        notifyUUID = "0783b03e-8535-b5a0-7140-a304f013c3b8"; //notify UUID
        //readUUID = "0783b03e-8535-b5a0-7140-a304f013c3ba"; //notify UUID
        //filterServiceUUID = "*E0";

        //这里介绍用name匹配方法
        //filterDeviceName = getNameMac(device_sn, 6, 'abc_'); //设备名称
    } else if (device_type === wxc_device_type || device_type === wxc_device_type_new) {
        serviceUUID[0] = "0000F040-0000-1000-8000-00805F9B34FB"; //主 service的uuid 列表
        writeUUID = "0000F041-0000-1000-8000-00805F9B34FB"; //写读 UUID
        //notifyUUID 		= "0000F042-0000-1000-8000-00805F9B34FB"; //notify UUID
        readUUID = "0000F042-0000-1000-8000-00805F9B34FB";// 读UUID
    }
}


/**
 * 初始化 值
 */
function initParam(device_sn_param, device_type_param, mkey = '') {
    device_sn = device_sn_param;
    device_type = device_type_param;
    device_key = mkey;
}


/**
* 初始化蓝牙模块
* 传递设备编号，设备类型
*/
function initBle(device_sn_param, device_type_param, mkey = '') {
    console.log('ble ----> 蓝牙初始化 initBle ');
    showLoading('搜索连接蓝牙...', 'initBle');
    //断开连接【每次初始化先断开连接】
    closeBLEConnection();
    //closeBLEAdapter();
    // 初始化 值
    initParam(device_sn_param, device_type_param, mkey);

    //调用主服务id相关
    setServicesUUID();

    _discoveryStarted = false;

    uni.openBluetoothAdapter({
        success: (res) => {
            startDiscovery();
            console.log('openBluetoothAdapter 初始化蓝牙模块是否成功:', res)
        },
        fail: (err) => {
            console.log('openBluetoothAdapter 初始化蓝牙模块是否失败:', err)
            errorCallback(err.errCode, "");

            /** 监听蓝牙变化 */
            //onBluetoothAdapterStateChange();
            if (err.error == 12) {


                uni.showModal({
                    title: '提示',
                    content: '请检查手机蓝牙是否打开',
                    showCancel: false
                })

            }
        },
        complete: (res) => {
            hideLoading('initBle');
        }
    });
}

/**
 * 监听蓝牙状态变化
 */
function onBluetoothAdapterStateChange() {
    //监听蓝牙适配器状态变化事件【根据需求是否执行】
    uni.onBluetoothAdapterStateChange(function (res) {
        console.log('onBluetoothAdapterStateChange() :  ', res)
        if (res.available) {
            console.log('蓝牙可用，搜索设备:--》 ', _discoveryStarted)
            if (!_discoveryStarted) {
                startDiscovery();
            }
        } else {

        }
    });
}

/**
 * 开锁搜索设备
 */
function startDiscovery() {
    onBluetoothDeviceFound();
    startBluetoothDevicesDiscovery();
}

/**
 * 监听寻找新设备事件
 * 注意咯： 这里有展示三种不同方式来连接设备，请看备注【mac, name, 根据系统的】 各取所需吧。
 */
function onBluetoothDeviceFound() {
    console.log('onBluetoothDeviceFound（） 方法');
    uni.onBluetoothDeviceFound((res) => {
        console.log('onBluetoothDeviceFound（） success----->', res);
        res.devices.forEach(device => {
            if (!device.name && !device.localName) {
                return
            }
            console.log('onBluetoothDeviceFound type----->' + device_type);
            if (device_type === sh_device_type) {
                if (device.advertisData) {
                    device.advertisData = buf2hex(device.advertisData);
                } else {
                    device.advertisData = '';
                }
                if (device_sn && device_sn == device.advertisData && isnotExist) {
                    isnotExist = false;
                    deviceId = device.deviceId;
                    //连接设备
                    createBLEConnection();
                }
            } else if (isYTDevice(device_type)) {
                console.log('广播数据结果 device.deviceName----->' + device.deviceName);
                if (device.name === device_sn.substr(0, 12)) {
                    isnotExist = false; // 不存在
                    deviceId = device.deviceId;
                    //连接设备
                    createBLEConnection();
                }
            } else if (device_type === wxc_device_type || device_type === wxc_device_type_new) {
                console.log('广播数据结果 device.deviceName----->', device.deviceName);
                console.log('广播数据结果 device.name----->', device.name);
                console.log('广播数据结果 device_sn----->', device_sn);
                console.log('广播数据结果 deviceId----->', device.deviceId);
                if (device.name === device_sn) {
                    isnotExist = false; // 不存在
                    deviceId = device.deviceId;
                    //连接设备
                    createBLEConnection();
                }
            }
        })
    },
        (err) => {
            console.log('onBluetoothDeviceFound（） 方法 error ', err);
        }
    )
}

/**
 * 执行连接蓝牙设备
 */
async function startBluetoothDevicesDiscovery() {
    console.log('startBluetoothDevicesDiscovery res _discoveryStarted----->', _discoveryStarted);
    if (_discoveryStarted) {
        return;
    }
    console.log('startBluetoothDevicesDiscovery res device_type----->', device_type);
    _discoveryStarted = true;

    if (isYTDevice(device_type)) { // 圆筒机
        uni.startBluetoothDevicesDiscovery({
            allowDuplicatesKey: false,
            success: (res) => {
                console.log('startBluetoothDevicesDiscovery success ', res);
            },
            fail: (res) => {
                errorCallback(res.errCode, "");
                console.log('startBluetoothDevicesDiscovery error ', res);
            },
            complete: (res) => {

            }
        });

    } else if (device_type === sh_device_type) { // 格子机 带ServicesUUID
        uni.startBluetoothDevicesDiscovery({
            services: ['FEE7'],
            allowDuplicatesKey: false,
            success: (res) => {
                console.log('startBluetoothDevicesDiscovery success ', res);
            },
            fail: (res) => {
                errorCallback(res.errCode, "");
                console.log('startBluetoothDevicesDiscovery error ', res);
            },
            complete: (res) => {

            }
        });

    } else if (device_type === wxc_device_type || device_type === wxc_device_type_new) {
        uni.startBluetoothDevicesDiscovery({
            allowDuplicatesKey: false,
            success: (res) => {
                console.log('startBluetoothDevicesDiscovery success ', res);
            },
            fail: (res) => {
                errorCallback(res.errCode, "");
                console.log('startBluetoothDevicesDiscovery error ', res);
            },
            complete: (res) => {

            }
        });
    }

}


//停止搜寻附近的蓝牙外围设备。
function stopBluetoothDevicesDiscovery(fromFunction) {
    console.log('stopBluetoothDevicesDiscovery() : fromFunction ' + fromFunction);
    uni.stopBluetoothDevicesDiscovery({
        success: (res) => {
            console.log('关闭蓝牙搜索, 结果  :', res)
        },
        fail(res) {
            console.log('stopBluetoothDevicesDiscovery fail', res);
        }
    })
}

// 获取蓝牙状态
function getBluetoothAdapterState() {
    uni.getBluetoothAdapterState({
        success: (res) => {
            console.log('getBluetoothAdapterState', res)
            if (res.discovering) {  // 正在搜索
                onBluetoothDeviceFound();
            } else if (res.available) { // 有效 
                startBluetoothDevicesDiscovery()
            }
        },
        fail(res) {
            console.log('getBluetoothAdapterState fail', res);
        }
    })
}


/**
 * 连接蓝牙设备
 */
async function createBLEConnection() {

    console.log('createBLEConnection connect() 方法', deviceId);
    showLoading('连接设备...', 'createBLEConnection');

    uni.createBLEConnection({
        deviceId: deviceId,
        success: (res) => {
            //获取蓝牙所有服务
            getBLEDeviceServices(deviceId);
        },
        fail: (res) => {
            errorCallback(res.errCode);
        },
        complete: () => {
            hideLoading('createBLEConnection');
        }
    });

    stopBluetoothDevicesDiscovery('createBLEConnection'); //停止搜索
}


/**
 * 关闭蓝牙适配器
 */
async function closeBLEAdapter() {
    try {
        let res = await uni.closeBluetoothAdapter();
        console.log("closeBLEAdapter ==>res:", res);
    } catch (res) {
        console.log("closeBLEAdapter ==>error:", res);
    }
    clearParam();
}
/**
 * 断开蓝牙连接
 */
async function closeBLEConnection() {
    //停止搜索
    stopBluetoothDevicesDiscovery('closeBLEConnection');

    //tempStr = ''; //清空

    if (deviceId) { // 连接了则关闭连接
        try {
            let res = await uni.closeBLEConnection();
            console.log("closeBLEConnection ==>res:", res);
        } catch (res) {
            console.log("closeBLEConnection ==>error:", res);
        }
        status = false;
    }
    try {
        let res = await uni.closeBluetoothAdapter();
        console.log("closeBLEAdapter ==>res:", res);
    } catch (res) {
        console.log("closeBLEAdapter ==>error:", res);
    }
    clearParam();
}

/**
 * 初始化参数
 */
function clearParam() {
    _discoveryStarted = false;
    isnotExist = true;
    _deviceId = '';
    deviceId = '';
    msg_id = 1;

    uni.$emit('event_ble_connect_changed', {
        connected: false
    })
}


/**
 * 获取蓝牙所有服务
 */
async function getBLEDeviceServices(deviceId) {

    // 连接状态监听
    uni.onBLEConnectionStateChange(function (res) {
        console.log("onBLEConnectionStateChange:", res);
        // 该方法回调中可以用于处理连接意外断开等异常情况
        console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
        if (res.connected == false) {
            console.log("连接意外断开等****", _deviceId);
            clearParam();
            /** 
            if (device_type == 1 && device_type == 2) {
                btErrorCallback(1010, ""); //?
            }*/
            showToast('与设备连接已断开,请查看蓝牙设备是否打开', 'getBLEDeviceServices.onBLEConnectionStateChange');
        }
    });

    uni.getBLEDeviceServices({
        deviceId: deviceId,
        success: (res) => {
            console.log("获取蓝牙设备所有服务(service)", res);
            for (let i = 0; i < res.services.length; i++) {
                let tmpUuid = res.services[i].uuid;
                if ((res.services[i].isPrimary) && (tmpUuid.indexOf(filterServiceUUID) != -1)) {
                    getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
                    return
                }
            }
        },
        fail: (res) => {
            console.log('getBLEDeviceServices fail', res);

            errorCallback(res.errCode);


        }
    })
}


/**
 * 获取蓝牙特征值
 */
function getBLEDeviceCharacteristics(deviceId, serviceId) {
    uni.getBLEDeviceCharacteristics({
        deviceId: deviceId,
        serviceId: serviceId,
        success: (res) => {
            console.log('蓝牙设备特征值信息:', res);
            uni.showToast({
                title: '设备连接成功',
            })

            uni.$emit('event_ble_connect_changed', {
                connected: true
            })
            getApp().globalData.connected = true;//存储蓝牙连接状态
            msg_id = 1;
            //setServicesUUID();
            for (let i = 0; i < res.characteristics.length; i++) {
                let item = res.characteristics[i]

                var itemUUID = item.uuid; //转小写
                if (device_type == sh_device_type) { //格子机
                    //powerBank.send(); //充电开机指令
                    itemUUID = itemUUID.toUpperCase(); // 转大写
                } else if (isYTDevice(device_type)) { //售卖机
                    itemUUID = itemUUID.toLowerCase(); //转小写
                } else if (device_type == wxc_device_type || device_type === wxc_device_type_new) { // 无线充电
                    itemUUID = itemUUID.toUpperCase(); // 转大写
                }
                console.log(i + ' notifyUUID ', notifyUUID);
                console.log(i + ' itemUUID ', itemUUID);
                console.log(i + ' item.properties', item.properties);
                console.log(i + ' item.properties.notify ', item.properties.notify);
                console.log(i + ' item.properties.indicate ', item.properties.indicate);
                console.log(i + ' item.properties.write ', item.properties.write);
                console.log(i + ' item.properties.read ', item.properties.read);
                if (notifyUUID === itemUUID && (item.properties.notify || item.properties.indicate)) { // 服务，监听数据变化
                    console.log('调用notifyBLECharacteristicValueChange前', item.uuid);
                    uni.notifyBLECharacteristicValueChange({
                        deviceId: deviceId,
                        serviceId: serviceId,
                        characteristicId: item.uuid,
                        state: true,
                        success(res) {
                            console.log('notification通知数据', res);
                            status = true;
                        },
                        fail(res) {
                            console.log('notifyBLECharacteristicValueChange fali', res);
                        }
                    })
                }
                if (item.properties.write && itemUUID === writeUUID) {
                    //console.log('蓝牙设备 访问 1：');
                    _deviceId = deviceId
                    _serviceId = serviceId
                    _characteristicId = item.uuid
                    console.log('蓝牙设备 访问 1 ：', _deviceId, _serviceId, _characteristicId);
                    //发送指令【说明：如需连接设备后发相关指令可以在这里调用】
                    if (device_type == sh_device_type) { //格子机
                        //powerBank.send(); //充电开机指令
                    } else if (isYTDevice(device_type)) { //售卖机
                        console.log('蓝牙设备 访问 2 ：');
                        vendingObj.checkConnect(); //握手指令
                    }
                }
                if (item.properties.read && itemUUID === readUUID) {
                    console.log('蓝牙设备 访问 1：');
                    // _deviceId = deviceId
                    // _serviceId = serviceId
                    // _characteristicId = item.uuid

                    //发送指令【说明：如需连接设备后发相关指令可以在这里调用】
                    if (device_type == sh_device_type) { //格子机
                        //powerBank.send(); //充电开机指令
                    } else if (isYTDevice(device_type)) { //售卖机
                        console.log('蓝牙设备 访问 2 ：');
                        //vendingObj.checkConnect(); //握手指令
                    } else if (device_type == wxc_device_type || device_type === wxc_device_type_new) { // 无线充						
                        // uni.readBLECharacteristicValue({
                        //     // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                        //     deviceId,
                        //     // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                        //     serviceId,
                        //     // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
                        //     characteristicId: item.uuid,
                        //     success(res) {
                        //         console.log('readBLECharacteristicValue ', res);
                        //         console.log('readBLECharacteristicValue:', res.errCode)
                        //     }
                        // })

                    }
                }
            }
        },
        fail: (res) => {
            console.log('getBLEDeviceCharacteristics fail', res)
            errorCallback(res.errCode);
        }
    })


    // 操作之前先监听，保证第一时间获取数据
    uni.onBLECharacteristicValueChange(function (res) {
        console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
        console.log("操作类型:" + action_type);

        var resData = ab2hex(res.value);
        console.log("设备返回数据--->", resData); //5d0000000001be304d
        // ff550e02010000000000000100a6
        // 判断不同类型处理数据
        if (isYTDevice(device_type)) {
            msg_id++;
            console.log('开始调用 自动售卖机====> 处理返回的数据');
            vendingObj.handleResData(resData); //处理返回数据
        } else if (device_type == sh_device_type) {
            vendingObjOne.handleResData(resData); //处理返回数据  
        } else if (device_type === wxc_device_type) {
            vendingObjTwo.handleResData(resData); //处理返回数据
        } else if (device_type === wxc_device_type_new) {
            vendingObjThree.handleResData(resData); //处理返回数据
        }
    })
}

/**
 * 检查是否打开蓝牙
 * 未连接设备前检测
 */
function checkIsOpenBluetooth(isEXec) {
    uni.openBluetoothAdapter({
        success: (res) => {
            isEXec(true);
        },
        fail: (res) => {
            uni.showModal({
                title: '提示',
                content: '请检查手机蓝牙是否打开',
                showCancel: false
            })
            isEXec(false);
        }
    })
}


/**
 * 蓝牙连接过程中错误码
 * 10000 / 10006
 */
function bluetoothStatus(errorType) {
    switch (errorType) {
        case 10001:
            showModal(
                '提示',
                '请检查手机蓝牙是否打开',
                'bluetoothStatus. errorType : 10001'
            );
            break;
        case 10002:
            showToast('没有找到指定设备', 'bluetoothStatus. errorType : 10002', 'none');
            break;
        case 10003:
            showToast('连接失败', 'bluetoothStatus. errorType : 10003');
            closeBLEConnection();
            break;
        case 10004:
            showToast('没有找到指定服务', 'bluetoothStatus. errorType : 10004');
            closeBLEConnection();
            break;
        case 10005:
            showToast('没有找到指定特征值', 'bluetoothStatus. errorType : 10005');
            closeBLEConnection();
            break;
        case 10007:
        case 10008:
        case 10013:
            showToast('设备启动失败，请重试', 'bluetoothStatus. errorType : 10007,8,13');
            break;
        case 10009:
            showModal(
                '提示',
                '当前系统版本过低，请更新版本体验',
                'bluetoothStatus. errorType : 10009'
            );
            break;
        case 10012:
            showToast('连接超时', 'bluetoothStatus. errorType : 10012');
            break;
    }
}

/**
 * 写入数据
 */
function writeData(hex, title = '', action = '') {
    console.log('writeData : _deviceId ', _deviceId);
    if (!status) {
        return;
    }
    if (!_deviceId) {
        btWriteCallback('w'); // 写入的时候，设备编号为空
        return;
    }

    if (title) {
        showLoading(title, 'writeData');
    }

    setTimeout(() => {
        //这里使用`TypedArray视图`中`Uint8Array（无符号 8 位整数）`操作
        console.log('writeBLECharacteristicValue ：', _deviceId, _serviceId, _characteristicId);
        var enDataBuf = new Uint8Array(hex);
        console.log('enDataBuf', enDataBuf);
        var buffer1 = enDataBuf.buffer;
        uni.writeBLECharacteristicValue({
            deviceId: _deviceId,
            serviceId: _serviceId,
            characteristicId: _characteristicId,
            value: buffer1,
            success: (res) => {
                if (btWriteCallback && action_type != OptionEnum.Recharge) {
                    btWriteCallback('success', currentOrderSN);
                }
                if (device_type == wxc_device_type) {
                    vendingObjTwo.readChargeStatus()
                } else if (device_type === wxc_device_type_new) {
                    vendingObjThree.readChargeStatus()
                }
                console.log("写数据返回结果", res);
            },
            fail(res) {
                console.log("写数据失败..", res);
                errorCallback(res.errCode, "");
            },
            complete: (res) => {
                if (title) {
                    hideLoading('writeData');
                }
            }
        })
    }, 500)
}

/**
 * 售卖机：圆筒机  数据类型：0x80
 */
var vendingObj = {
    /**
     * 链接握手
     */
    checkConnect: function () {
        // 0x5C,0x5F,0x57,0x59,0x5E
        console.log('checkConnect 访问：');
        status = true;
        let buff_array = [];
        buff_array.push(0xFF); // 1
        buff_array.push(0x55); // 2
        buff_array.push(0x12); // 3
        buff_array.push(0x01); // 4
        buff_array.push(parseInt(msg_id, 16));
        buff_array.push(parseInt(device_sn.substr(0, 2), 16));// 设备号1
        buff_array.push(parseInt(device_sn.substr(2, 2), 16));// 设备号2
        buff_array.push(parseInt(device_sn.substr(4, 2), 16));// 设备号3
        buff_array.push(parseInt(device_sn.substr(6, 2), 16));// 设备号4
        buff_array.push(parseInt(device_sn.substr(8, 2), 16));// 设备号5
        buff_array.push(parseInt(device_sn.substr(10, 2), 16));// 设备号6
        buff_array.push(0x01);// 指令
        buff_array.push(0x5C);// 固定数据
        buff_array.push(0x5F);// 固定数据
        buff_array.push(0x57);// 固定数据
        buff_array.push(0x59);// 固定数据
        buff_array.push(0x5E);// 固定数据      
        buff_array.push(parseInt(bufCheckXor(buff_array), 16)); // 校验位
        console.log('握手的指令：', buff_array);
        //var cryptoKey = new Uint8Array(key);
        //enKEY = cryptoKey;
        //得出加密后的指令, 十六进制的数据
        //var enHEX = cryptoService.updateEncrypt(strKey, enKEY);
        writeData(buff_array);
    },
    /**
     * 查询设备信息
     */
    queryDeviceInfo: function () {
        action_type = OptionEnum.ReadBattery; //改变操作类型
        let hex = [0x69, 0xf2, 0x00, 0x89];
        writeData(hex); //写入数据
    },

    /**
    * 开锁指令
    */
    openVendingLock: function (callBack, channel, order_sn = '') {
        //device_sn = '611297060137'
        currentSerialVal = channel;
        currentOrderSN = order_sn;
        status = true;
        action_type = OptionEnum.VendingOpenLock; // 开锁
        btOpenCallback = callBack;
        //获取当前开锁的编号及转换
        //let getCurrentVal = Number(currentSerialVal);
        //getCurrentVal = getCurrentVal.toString(16);
        // let tempVal = '0x0' + getCurrentVal;
        let tempVal = parseInt(channel, 16);
        console.log('====开锁编号===》', tempVal);
        let buff_array = [];
        buff_array.push(0xFF); // 1
        buff_array.push(0x55); // 2
        buff_array.push(0x12); // 3
        buff_array.push(0x01); // 4 ： 上位机 --> 设备
        buff_array.push(parseInt(msg_id, 16));       // 消息序列号
        buff_array.push(parseInt(device_sn.substr(0, 2), 16));// 设备号1
        buff_array.push(parseInt(device_sn.substr(2, 2), 16));// 设备号2
        buff_array.push(parseInt(device_sn.substr(4, 2), 16));// 设备号3
        buff_array.push(parseInt(device_sn.substr(6, 2), 16));// 设备号4
        buff_array.push(parseInt(device_sn.substr(8, 2), 16));// 设备号5
        buff_array.push(parseInt(device_sn.substr(10, 2), 16));// 设备号6
        buff_array.push(0x02);// 指令
        buff_array.push(0x00);// 固定数据
        buff_array.push(0x00);// 固定数据
        buff_array.push(tempVal);// 固定数据
        buff_array.push(0x00);// 固定数据
        buff_array.push(0x00);// 固定数据      
        buff_array.push(parseInt(bufCheckXor(buff_array), 16)); // 校验位
        writeData(buff_array, '正在出货...');
    },
    /**
   * 全开锁指令
   */
    openAllLock: function (callBack) {
        status = true;
        action_type = OptionEnum.VendingOpenLock; // 开锁
        btOpenCallback = callBack;
        //获取当前开锁的编号及转换
        //let getCurrentVal = Number(currentSerialVal);
        //getCurrentVal = getCurrentVal.toString(16);
        // let tempVal = '0x0' + getCurrentVal;0xB1,0xB2,0xB3,0xB4,0xB5
        let buff_array = [];
        buff_array.push(0xFF); // 1
        buff_array.push(0x55); // 2
        buff_array.push(0x12); // 3
        buff_array.push(0x01); // 4 ： 上位机 --> 设备
        buff_array.push(parseInt(msg_id, 16));       // 消息序列号
        buff_array.push(parseInt(device_sn.substr(0, 2), 16));// 设备号1
        buff_array.push(parseInt(device_sn.substr(2, 2), 16));// 设备号2
        buff_array.push(parseInt(device_sn.substr(4, 2), 16));// 设备号3
        buff_array.push(parseInt(device_sn.substr(6, 2), 16));// 设备号4
        buff_array.push(parseInt(device_sn.substr(8, 2), 16));// 设备号5
        buff_array.push(parseInt(device_sn.substr(10, 2), 16));// 设备号6
        buff_array.push(0x04);// 指令
        buff_array.push(0xB1);// 固定数据
        buff_array.push(0xB2);// 固定数据
        buff_array.push(0xB3);// 固定数据
        buff_array.push(0xB4);// 固定数据
        buff_array.push(0xB5);// 固定数据      
        buff_array.push(parseInt(bufCheckXor(buff_array), 16)); // 校验位
        console.log('全开锁指令：', buff_array);
        console.log('全开始指令：', buf2hex(buff_array));
        writeData(buff_array);
    },

    /**
     * 处理格子机查询信息电量回调
     * 目的：获取到相关数据，发送给后端（查看设备电量）
     */
    readBatteryCallBack: function (battery) {
        console.log("=======>>>电量:", battery);
        action_type = OptionEnum.None;

        //这里获取到电量, 返回给index.js页面
        if (btOpenCallback != null) {
            btOpenCallback(battery, OptionEnum.ReadBattery);
        } else {
            console.log("是否为空=======标签 2");
        }
    },

    /**
     * 处理开锁成功回调
     */
    openLockCallback: function (resData) {
        console.log('openLockCallback开锁回调 数据 ', resData);
        var isOpenLock = false;
        if (resData) {
            var length = resData.length;
            var cmd = resData.substr(length - 6, 2);
            var status = resData.substr(length - 4, 2);

            if ((cmd == '02' || cmd == '04') && status == '03') {
                isOpenLock = true;
            }
            action_type = OptionEnum.None;
        }
        if (btOpenCallback != null) {
            btOpenCallback(isOpenLock, OptionEnum.VendingOpenLock, currentSerialVal, currentOrderSN);
        }
    },

    //充电指令
    rechargeDevice: function (time, callback) {
        console.log('准备写入充电指令，time=', time)
        //转16进制
        let hexTime = '0x' + parseInt(time).toString(16)
        console.log('充电时间转16进制：', hexTime)

        status = true;
        action_type = OptionEnum.Recharge; // 充电
        btRechargeCallback = callback;

        let buff_array = [];
        buff_array.push(0xFF); // 1
        buff_array.push(0x55); // 2
        buff_array.push(0x12); // 3
        buff_array.push(0x01); // 4 ： 上位机 --> 设备
        buff_array.push(parseInt(msg_id, 16));       // 消息序列号
        buff_array.push(parseInt(device_sn.substr(0, 2), 16));// 设备号1
        buff_array.push(parseInt(device_sn.substr(2, 2), 16));// 设备号2
        buff_array.push(parseInt(device_sn.substr(4, 2), 16));// 设备号3
        buff_array.push(parseInt(device_sn.substr(6, 2), 16));// 设备号4
        buff_array.push(parseInt(device_sn.substr(8, 2), 16));// 设备号5
        buff_array.push(parseInt(device_sn.substr(10, 2), 16));// 设备号6
        buff_array.push(0x05);// 指令
        buff_array.push(0x00);// 固定数据
        buff_array.push(0x00);// 固定数据
        buff_array.push(0x00);// 固定数据
        buff_array.push(hexTime);// 固定数据
        buff_array.push(0x00);// 固定数据
        buff_array.push(parseInt(bufCheckXor(buff_array), 16)); // 校验位
        console.log('充电指令：', buff_array);
        console.log('充电指令：', buf2hex(buff_array));
        writeData(buff_array);
    },

    /**
     * 处理充电回调
     */
    rechargeCallback: function (resData) {
        console.log('充电指令回调，res=', resData)

        if (resData) {
            var length = resData.length;
            var cmd = resData.substr(length - 6, 2);
            var status = resData.substr(length - 4, 2);

            console.log('充电指令回调，cmd=', cmd, ' status=', status)
            if (cmd == '05' && status == '06') {
                //充电成功
                if (btRechargeCallback != null) {
                    btRechargeCallback()
                }
            }

            action_type = OptionEnum.None;
        }
    },

    /**
     * 处理返回数据
     * 例如： 00f05d09000001be304d
     * ff550e02010000000000000100a6
     */
    handleResData: function (resData) {
        let checkStatus = resData.substring(2, 4);

        if (checkStatus.toUpperCase() == 'F0' && action_type == OptionEnum.Connection) { //校验状态
            vendingObj.queryDeviceInfo(); //查询设备信息

        } else if (action_type == OptionEnum.ReadBattery) { //操作的是获取设备电量

            let batteryVal = resData.substring(6, 8);
            batteryVal = parseInt(batteryVal, 16);
            vendingObj.readBatteryCallBack(batteryVal);

        } else if (action_type == OptionEnum.VendingOpenLock) { //操作的是 开锁

            vendingObj.openLockCallback(resData);
        } else if (action_type == OptionEnum.Recharge) {
            vendingObj.rechargeCallback(resData)
        }
    }
}

/**
 * 售货机：口罩机， 设备类型： 0x65,64
 */
var vendingObjOne = {
    /**
     * 查询设备信息
     */
    queryDeviceInfo: function () {
        //action_type = OptionEnum.ReadBattery; //改变操作类型
        //let hex = [0x69, 0xf2, 0x00, 0x89];
        //writeData(hex); //写入数据
    },

    /**
    * 开锁指令
    */
    openVendingLock: function (callBack, channel, order_sn = '', led = 1, led_time = 10) {
        currentSerialVal = channel;
        currentOrderSN = order_sn ? order_sn : getOrdersn(18, 100);
        status = true;
        action_type = OptionEnum.VendingOpenLock; // 开锁
        btOpenCallback = callBack;
        //获取当前开锁的编号及转换
        let tempVal = parseInt(channel, 16);
        let buff_array = [];
        buff_array.push(0x7E); // 1 帧头
        buff_array.push(0x01); // 2 上位机 --> 设备
        buff_array.push(parseInt(device_sn.substr(4, 2), 16));// 3 设备号1
        buff_array.push(parseInt(device_sn.substr(6, 2), 16));// 4 设备号2
        buff_array.push(parseInt(device_sn.substr(8, 2), 16));// 5 设备号3
        buff_array.push(parseInt(device_sn.substr(10, 2), 16));// 6 设备号4
        buff_array.push(parseInt(device_sn.substr(12, 2), 16));// 7 设备号5
        buff_array.push(parseInt(device_sn.substr(14, 2), 16));// 8 设备号6
        buff_array.push(0x00);  // 9  固定数据
        buff_array.push(0x00);  // 10 固定数据
        buff_array.push(0xA0);  // 11 开锁指令
        buff_array.push(tempVal);// 12 格子编号
        buff_array.push(parseInt(led, 16));   //  13 灯是否亮  
        buff_array.push(parseInt(led_time, 10));   //  14 亮灯时长
        buff_array.push(parseInt(currentOrderSN.substr(0, 2), 10));// 15 订单编号1
        buff_array.push(parseInt(currentOrderSN.substr(2, 2), 10));// 16 订单编号2
        buff_array.push(parseInt(currentOrderSN.substr(4, 2), 10));// 17 订单编号3
        buff_array.push(parseInt(currentOrderSN.substr(6, 2), 10));// 18 订单编号4 
        buff_array.push(0x00);  // 19 保留位 
        let check = crc.veri(new Uint8Array(buff_array), device_key);
        buff_array.push(parseInt(check.substr(2, 2), 16)); // 校验位
        //console.log('open 2 ');
        writeData(buff_array, '正在出货...');
    },
    /**
     * 处理格子机查询信息电量回调
     * 目的：获取到相关数据，发送给后端（查看设备电量）
     */
    readBatteryCallBack: function (battery) {
        console.log("=======>>>电量:", battery);
        action_type = OptionEnum.None;

        //这里获取到电量, 返回给index.js页面
        if (btOpenCallback != null) {
            btOpenCallback(battery, OptionEnum.ReadBattery);
        } else {
            console.log("是否为空=======标签 2");
        }
    },

    /**
     * 处理开锁成功回调
     */
    openLockCallback: function (resData) { //  7e02feef3c0819849b01 b0 00 01 14 15 04 11 00 00 ea
        //7e02feef3c0819849b01b0 00 01 2a 2f 1c 26 00 00 82
        console.log('openLockCallback开锁回调 数据 ', resData);
        var isOpenLock = false;
        if (resData) {
            var length = resData.length;

            var cmd = resData.substr(length - 20, 2).toLowerCase();
            var status = resData.substr(length - 18, 2);
            console.log('开锁命令 ', cmd + " , 开锁状态 ： " + status);
            if ((cmd == 'b0'.toLowerCase()) && status == '00') {
                isOpenLock = true;
            }
            action_type = OptionEnum.None;
        }
        if (btOpenCallback != null) {
            btOpenCallback(isOpenLock, OptionEnum.VendingOpenLock, currentSerialVal, currentOrderSN);
        }
    },

    /**
     * 处理返回数据
     * 例如： 00f05d09000001be304d
     * ff550e02010000000000000100a6
     * 
     */
    handleResData: function (resData) { // 7e02feef3c0819849b01b000012a2f0317000017
        let checkStatus = resData.substring(2, 4);

        if (checkStatus.toUpperCase() == 'F0' && action_type == OptionEnum.Connection) { //校验状态
            vendingObjOne.queryDeviceInfo(); //查询设备信息

        } else if (action_type == OptionEnum.ReadBattery) { //操作的是获取设备电量

            let batteryVal = resData.substring(6, 8);
            batteryVal = parseInt(batteryVal, 16);
            vendingObjOne.readBatteryCallBack(batteryVal);

        } else if (action_type == OptionEnum.VendingOpenLock) { //操作的是 开锁

            vendingObjOne.openLockCallback(resData);
        }
    }
}

/**
 * 售货机：无线充， 设备类型： 0x88
 */
var vendingObjTwo = {
    //充电指令
    rechargeDevice: function (hour, min, callback) {
        console.log('准备写入充电指令，min=', min)
        console.log('准备写入充电指令，hour=', hour)
        //转16进制
        let hexHour = 0x00;
        if (hour > 0) {
            hexHour = '0x' + parseInt(hour).toString(16);
        }
        let hexMin = 0x00;
        if (min > 0) {
            hexMin = '0x' + parseInt(min).toString(16);
        }
        console.log('充电时间转16进制：', hexHour, hexMin)

        status = true;
        action_type = OptionEnum.Recharge; // 充电
        btRechargeCallback = callback;

        let buff_array = [];
        buff_array.push(0xFE); // 1
        buff_array.push(0xD5); // 2
        buff_array.push(hexHour); // 3  小时 0x00~0x30  0~48小时 最大支持48小时
        buff_array.push(hexMin); // 4  分钟 0x00~0x3c  0~60分钟
        buff_array.push(0x00);  // 5 固定数据
        buff_array.push(0x00);	// 6 固定数据
        buff_array.push(0x00);	// 7 固定数据
        buff_array.push(0x00);	// 8 固定数据
        buff_array.push(0x00);  // 9 固定数据
        buff_array.push(0x00);	// 10 固定数据
        buff_array.push(0x00);  // 11 固定数据
        buff_array.push(0x00);	// 12 固定数据
        buff_array.push(0x00);	// 13 固定数据
        buff_array.push(0x00);	// 14 固定数据
        buff_array.push(0x00);  // 15 固定数据
        buff_array.push(0x00);	// 16 固定数据
        buff_array.push(0x00);	// 17 固定数据
        buff_array.push(0x00);  // 18 固定数据
        buff_array.push(0x00);	// 19 固定数据
        buff_array.push(0X45); // 校验位
        console.log('充电指令：', buff_array);
        console.log('充电指令：', buf2hex(buff_array));
        writeData(buff_array);
    },

    /**
     * 处理充电回调
     */
    rechargeCallback: function (resData) {
        console.log('充电指令回调，res=', resData)
        if (resData && (action_type == OptionEnum.ReadRecharge || action_type == OptionEnum.ReadRechargeCallback)) {
            var length = resData.length;
            //var cmd = resData.substr(length - 6, 2);
            var status = resData.substr(length - 2, 2);

            console.log('充电指令回调 status=', status)
            if (status == '46') {
                //充电成功
                if (action_type == OptionEnum.ReadRecharge) {
                    if (btRechargeCallback != null) {
                        btRechargeCallback(true);
                    }
                } else if (action_type == OptionEnum.ReadRechargeCallback) {
                    if (readRechargeCallback != null) {
                        readRechargeCallback(true);
                    }
                }


            }
            if (status == '00') {
                //充电失败
                if (action_type == OptionEnum.ReadRecharge) {
                    if (btRechargeCallback != null) {
                        btRechargeCallback(false);
                    }
                } else if (action_type == OptionEnum.ReadRechargeCallback) {
                    if (readRechargeCallback != null) {
                        readRechargeCallback(false);
                    }
                }

            }

            action_type = OptionEnum.None;
        }
    },


    /**
     * 处理返回数据
充电状态中：
FE D5 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46
没有充电中：
FE D5 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

     * 
     */
    handleResData: function (resData) { // 7e02feef3c0819849b01b000012a2f0317000017 
        vendingObjTwo.rechargeCallback(resData);
    },
    readChargeStatus: function (flag) {
        // 无线充						
        console.log("🚀 ~ 无线充   开始读状态",)
        uni.readBLECharacteristicValue({
            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
            deviceId: _deviceId,
            // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
            serviceId: _serviceId,
            // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
            characteristicId: readUUID,
            success(res) {
                action_type = flag ? OptionEnum.ReadRechargeCallback : OptionEnum.ReadRecharge;
                console.log('readBLECharacteristicValue ', res);
                console.log('readBLECharacteristicValue:', res.errCode)
                if (res.errno === 1509000) {//未充电，直接回调
                    if (readRechargeCallback != null) {
                        readRechargeCallback(false);
                    }
                }
            }
        })


    }
}
/**
 *无线充， 设备类型： 0x89
 */
var vendingObjThree = {
    //充电指令
    rechargeDevice: function (hour, min, callback) {
        console.log('准备写入充电指令，min=', min)
        console.log('准备写入充电指令，hour=', hour)
        //转16进制
        let hexHour = 0x00;
        if (hour > 0) {
            hexHour = '0x' + parseInt(hour).toString(16);
        }
        let hexMin = 0x00;
        if (min > 0) {
            hexMin = '0x' + parseInt(min).toString(16);
        }
        console.log('充电时间转16进制：', hexHour, hexMin)

        status = true;
        action_type = OptionEnum.Recharge; // 充电
        btRechargeCallback = callback;

        let buff_array = [];
        buff_array.push(0xA0); // 1
        buff_array.push(0xD5); // 2
        buff_array.push(hexHour); // 3  小时 0x00~0x30  0~48小时 最大支持48小时
        buff_array.push(hexMin); // 4  分钟 0x00~0x3c  0~60分钟
        buff_array.push(0x00);  // 5 固定数据
        buff_array.push(0x00);	// 6 固定数据
        buff_array.push(0x00);	// 7 固定数据
        buff_array.push(0x00);	// 8 固定数据
        buff_array.push(0x00);  // 9 固定数据
        buff_array.push(0x00);	// 10 固定数据
        buff_array.push(0x00);  // 11 固定数据
        buff_array.push(0x00);	// 12 固定数据
        buff_array.push(0x00);	// 13 固定数据
        buff_array.push(0x00);	// 14 固定数据
        buff_array.push(0x00);  // 15 固定数据
        buff_array.push(0x00);	// 16 固定数据
        buff_array.push(0x00);	// 17 固定数据
        buff_array.push(0x00);  // 18 固定数据
        buff_array.push(0x00);	// 19 固定数据
        buff_array.push(0X45); // 校验位
        console.log('充电指令：', buff_array);
        console.log('充电指令：', buf2hex(buff_array));
        writeData(buff_array);
    },

    /**
     * 处理充电回调
     */
    rechargeCallback: function (resData) {
        console.log('充电指令回调，res=', resData)
        if (resData && (action_type == OptionEnum.ReadRecharge || action_type == OptionEnum.ReadRechargeCallback)) {
            var length = resData.length;
            //var cmd = resData.substr(length - 6, 2);
            var status = resData.substr(length - 2, 2);

            console.log('充电指令回调 status=', status)
            if (status == '46') {
                //充电成功
                if (action_type == OptionEnum.ReadRecharge) {
                    if (btRechargeCallback != null) {
                        btRechargeCallback(true);
                    }
                } else if (action_type == OptionEnum.ReadRechargeCallback) {
                    if (readRechargeCallback != null) {
                        readRechargeCallback(true);
                    }
                }


            }
            if (status == '00') {
                //充电失败
                if (action_type == OptionEnum.ReadRecharge) {
                    if (btRechargeCallback != null) {
                        btRechargeCallback(false);
                    }
                } else if (action_type == OptionEnum.ReadRechargeCallback) {
                    if (readRechargeCallback != null) {
                        readRechargeCallback(false);
                    }
                }

            }

            action_type = OptionEnum.None;
        }
    },


    /**
     * 处理返回数据
充电状态中：
FE D5 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 46
没有充电中：
FE D5 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

     * 
     */
    handleResData: function (resData) { // 7e02feef3c0819849b01b000012a2f0317000017 
        vendingObjTwo.rechargeCallback(resData);
    },
    readChargeStatus: function (flag) {
        // 无线充						
        console.log("🚀 ~ 无线充   开始读状态",)
        uni.readBLECharacteristicValue({
            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
            deviceId: _deviceId,
            // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
            serviceId: _serviceId,
            // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
            characteristicId: readUUID,
            success(res) {
                action_type = flag ? OptionEnum.ReadRechargeCallback : OptionEnum.ReadRecharge;
                console.log('readBLECharacteristicValue ', res);
                console.log('readBLECharacteristicValue:', res.errCode)
                if (res.errno === 1509000) {//未充电，直接回调
                    if (readRechargeCallback != null) {
                        readRechargeCallback(false);
                    }
                }
            }
        })


    }
}
//读取充电状态
function readChargeStatus(callback) {
    readRechargeCallback = callback
    if (device_type === wxc_device_type) {

        vendingObjTwo.readChargeStatus(true);
    } else if (device_type === wxc_device_type_new) {

        vendingObjThree.readChargeStatus(true);
    }
}


function strCheckXor(str) { // 异或运算
    var list = [];
    var ar2 = 0;
    for (let i = 0; i < str.length - 1; i += 2) {
        list.push(parseInt((str.substring(i, i + 2)), 16)) //将字符串切割为两位字符的数组并转为16进制的整型。
    }
    for (let j = 0; j < list.length; j++) {
        ar2 ^= list[j] //前两位的数组的异或结果在和第三位数组异或，以此类推得到最终结果
    }
    return parseInt(ar2).toString(16) //将得到结果进行整型，转为16进制得到最终结果
}
function bufCheckXor(buff_array) {
    var ar2 = 0;
    for (let j = 0; j < buff_array.length; j++) {
        ar2 ^= buff_array[j] //前两位的数组的异或结果在和第三位数组异或，以此类推得到最终结果
    }
    return parseInt(ar2).toString(16) //将得到结果进行整型，转为16进制得到最终结果
}
// 二进制处理方法
function buf2hex(buffer) { // buf转16进制
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('')
}

//取16位 订单号
function getOrdersn(minNum, maxNum) {
    var today = new Date();
    var day = today.getDate(); //获取当前日(1-31)      
    var month = today.getMonth() + 1; //显示月份比实际月份小1,所以要加1  
    var year = today.getYear();  //获取完整的年份(4位,1970-????)  getFullYear()
    var years = today.getFullYear();
    years = years < 99 ? "20" + years : years;
    month = month < 10 ? "0" + month : month;  //数字<10，实际显示为，如5，要改成05  
    day = day < 10 ? "0" + day : day;
    var hh = today.getHours();
    hh = hh < 10 ? "0" + hh : hh;
    var ii = today.getMinutes();
    ii = ii < 10 ? "0" + ii : ii;
    var ss = today.getSeconds();
    ss = ss < 10 ? "0" + ss : ss;
    var dada = years.toString() + month.toString() + day.toString() + hh.toString() + ii.toString() + ss.toString();
    switch (arguments.length) {
        case 1:
            return dada + parseInt(Math.random() * minNum + 1, 10);
            break;
        case 2:
            return dada + parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            break;
        default:
            return 0;
            break;
    }
}

/***
 * 设备开锁接口回调
 */
function openOneLock(callBack, channel, order_sn = null, led = 1, led_time = 10) {
    console.log('蓝牙开门 ');
    //device_type = '0x80'
    if (device_type === sh_device_type) {
        vendingObjOne.openVendingLock(callBack, channel, order_sn, led, led_time);
    } else if (isYTDevice(device_type)) {
        vendingObj.openVendingLock(callBack, channel, order_sn);
    }
}

/***
 * 设备开锁接口回调
 */
function openAllLock(callBack) {
    if (device_type === sh_device_type) {
        //vendingObjOne.openVendingLock(callBack,channel,order_sn ,led, led_time);
    } else if (isYTDevice(device_type)) {
        vendingObj.openAllLock(callBack);
    }
}


/***
 * 设备充电回调
 */
function rechargeDevice(time, callback, hour = 0) {
    console.log('rechargeDevice', device_type);
    if (device_type === sh_device_type) {
        //vendingObjOne.openVendingLock(callBack,channel,order_sn ,led, led_time);
    } else if (isYTDevice(device_type)) {
        console.log('准备调用vendingObj的rechargeDevice方法')
        vendingObj.rechargeDevice(time, callback);
    } else if (device_type === wxc_device_type) {
        console.log('准备调用vendingObjTwo的rechargeDevice方法')
        vendingObjTwo.rechargeDevice(hour, time, callback);
    } else if (device_type === wxc_device_type_new) {
        vendingObjThree.rechargeDevice(hour, time, callback);
    }
}


//设置连接
function setConnectionActionType(callBack) {
    action_type = OptionEnum.Connection;
    btOpenCallback = callBack;
}

//设置重连
function setReconnectionActionType() {
    action_type = OptionEnum.Reconnection;
}

// 设置错误
function setbtErrorCallback(callBack) {
    btErrorCallback = callBack;
}

//设置关闭
function setCloseActionType(callBack) {
    action_type = OptionEnum.CloseLock;
    btOpenCallback = callBack;
}

//设置写入错误
function setWriteCallback(callBack) {
    btWriteCallback = callBack;
}

// 显示Loading
function showLoading(tip, methodName = '') {
    uni.showLoading({
        title: tip,
        success: (res) => {
            console.log('方法名 ' + methodName + ' showLoading Succcess ', res);
        },
        fail: (res) => {
            console.log('方法名 ' + methodName + ' showLoading fail ', res);
        }
    });
}

// 隐藏Loading  
function hideLoading(methodName = '') {
    uni.hideLoading({
        success: (res) => {
            console.log('方法名 ' + methodName + ' hideLoading Succcess ', res);
        },
        fail: (res) => {
            console.log('方法名 ' + methodName + ' hideLoading fail ', res);
        }
    });
}


// 显示Toast
function showToast(tip, methodName = '', icon_value = 'none') {
    uni.showToast({
        title: tip,
        icon: icon_value,
        success: (res) => {
            console.log('方法名 ' + methodName + ' showToast Succcess ', res);
        },
        fail: (res) => {
            console.log('方法名 ' + methodName + ' showToast fail ', res);
        }
    });
}

// 显示Model
function showModal(tip, cont, methodName = '') {
    uni.showModal({
        title: tip,
        content: cont,
        showCancel: false,
        success: (res) => {
            console.log('方法名 ' + methodName + ' showToast Succcess ', res);
        },
        fail: (res) => {
            console.log('方法名 ' + methodName + ' showToast fail ', res);
        }
    })
}

function errorCallback(errCode) {
    if (btErrorCallback) {
        btErrorCallback(errCode, "");
    } else {
        bluetoothStatus(errCode);
    }
}

//清除
function clearCallBack() {
    btOpenCallback = null;
}

function isBlueDevice(device_type_param) {
    console.log('isBlueDevice----->' + device_type_param);
    return device_type_param === sh_device_type ||
        isYTDevice(device_type_param) || device_type_param === wxc_device_type || device_type_param === wxc_device_type_new;
}

// 是否有充电功能
function isRechargeDevice(device_type_param) {
    return device_type_param == yt_recharge_device_type || device_type_param == wxc_device_type || device_type_param === wxc_device_type_new;
}

export default {
    initBle: initBle,
    clearCallBack: clearCallBack,
    closeBLEConnection: closeBLEConnection,
    setConnectionActionType: setConnectionActionType,
    setReconnectionActionType: setReconnectionActionType,
    setBtErrorCallback: setbtErrorCallback,
    setCloseActionType: setCloseActionType,
    setWriteCallback: setWriteCallback,
    checkIsOpenBluetooth: checkIsOpenBluetooth,
    bluetoothStatus: bluetoothStatus,
    openVendingLock: openOneLock,
    openAllLock: openAllLock,
    isBlueDevice: isBlueDevice,
    rechargeDevice: rechargeDevice,
    isRechargeDevice: isRechargeDevice,
    readChargeStatus: readChargeStatus
}